package dlt645_v2007_master_connector

import (
	"encoding/json"
	"go-iot-gateway/internal/apk/maths"
	"go-iot-gateway/internal/channel"
	channel_define "go-iot-gateway/internal/channel/define"
	conf_table_define "go-iot-gateway/internal/conf_table/define"
	"go-iot-gateway/internal/logger"
	sys_config "go-iot-gateway/internal/sys/config"
	dlt "go-iot-gateway/pkg/dlt645_2007"
	"strings"
	"time"
)

func NewDlt6452007MasterConnector(channelConfig conf_table_define.ChannelInfo,
	protocolConfInfos []*conf_table_define.ProtocolInfo) (channel_define.ConnectChannel, error) {
	serialAddrAlias := sys_config.ConfigInfo().SerialAddrAlias

	connectParams := channel_define.ConnectParams{}
	err := json.Unmarshal([]byte(channelConfig.Chl_main_param), &connectParams)
	if err != nil {
		return nil, err
	}

	channelInfo := channel_define.ChannelInfo{}

	channelInfo.ChlId = channelConfig.Chl_id
	channelInfo.Name = channelConfig.Chl_name
	channelInfo.Addr = channelConfig.Chl_addr
	channelInfo.Desc = channelConfig.Chl_desc
	channelInfo.Protocol = strings.TrimSpace(channelConfig.Chl_protocol)
	channelInfo.SetStatus(channel_define.CONNECT_STATUS_CREATE, "已创建")
	channelInfo.ChannelType = channelConfig.Chl_type
	channelInfo.ProtocolType = channelConfig.Protocol_type
	channelInfo.Frequency = channelConfig.Chl_colt_freq
	channelInfo.WaitTime = channelConfig.Chl_wait_time
	channelInfo.ConnectParams = connectParams

	chl := &Dlt6452007MasterChannel{}
	chl.protocolInfo = NewRTU2007ProtocolInfo(protocolConfInfos)
	chl.ChannelInfo = channelInfo
	chl.channelManager = channel.Manager()
	chl.isClosed = false
	chl.logger = logger.NewChannelLogger(channelConfig.Chl_name)

	//windows 下面就是 com开头的，比如说 com3
	//mac OS/linux/unix  下面就是 /dev/下面的，比如说 dev/tty.usbserial-14320

	rtuDevice := serialAddrAlias.SerialAddr(chl.ChannelInfo.ConnectParams.ComName)
	chl.ChannelInfo.ConnectParams.ComName = rtuDevice
	handler := dlt.NewClient2007Handler(rtuDevice)
	handler.SerialParams.SerialName = rtuDevice
	handler.SerialParams.BaudRate = int(chl.ChannelInfo.ConnectParams.Baud)
	handler.SerialParams.DataBits = chl.ChannelInfo.ConnectParams.DataBit
	handler.SerialParams.StopBits = chl.ChannelInfo.ConnectParams.StopBit
	handler.SerialParams.Parity = chl.ChannelInfo.ConnectParams.CheckBit
	handler.SerialParams.ReadTimeout = time.Duration(chl.ChannelInfo.ConnectParams.Timeout) * time.Millisecond
	handler.Logger = chl.logger

	chl.handler = handler
	idleTime := maths.MaxInt(channelInfo.Frequency, channelInfo.ConnectParams.Timeout)
	chl.handler.IdleTimeout = time.Duration(idleTime+7000) * time.Millisecond

	chl.client = dlt.NewClient(handler)

	return chl, nil
}
